'use strict';
import Base from './base.js';

export default class extends Base {
  /*
  * 基础设置
  */
  async basisAction() {
    const shopid = this.shop_userinfo.departmentid;
    // 获取积分增加比
    const basis = await this.model('or_shop_basis').where({shopid: shopid}).find();

    if (think.isEmpty(basis)) {
      return this.json({'code': 0});
    } else {
      return this.json({'code': 200, 'data': basis});
    }
  }

  // 设置积分比
  async setintegralAction() {
    const bl = this.post('bl') / 100;
    const shopid = this.shop_userinfo.departmentid;
    const model = this.model('or_shop_basis');
    const basisInfo = await model.where({shopid: shopid}).find();
    let res = 1;

    if (think.isEmpty(basisInfo)) {
      res = await model.add({shopid: shopid, jifenpercent: bl});
    } else {
      res = await model.where({id: basisInfo.id}).update({'jifenpercent': bl});
    }

    return res ? this.success('设置成功') : this.fail('设置失败');
  }

  // 设置充值提成比
  async setchongzhiAction() {
    const bl = this.post('bl') / 100;
    const shopid = this.shop_userinfo.departmentid;
    const model = this.model('or_shop_basis');
    const basisInfo = await model.where({shopid: shopid}).find();
    let res = 1;

    if (think.isEmpty(basisInfo)) {
      res = await model.add({shopid: shopid, chongzhipercent: bl});
    } else {
      res = await model.where({id: basisInfo.id}).update({'chongzhipercent': bl});
    }

    return res ? this.success('设置成功') : this.fail('设置失败');
  }

  async setopencardAction() {
    const bl = this.post('bl') / 100;
    const shopid = this.shop_userinfo.departmentid;
    const model = this.model('or_shop_basis');
    const basisInfo = await model.where({shopid: shopid}).find();
    let res = 1;
    if (think.isEmpty(basisInfo)) {
      res = await model.add({shopid: shopid, kaikapercent: bl});
    } else {
      res = await model.where({id: basisInfo.id}).update({'kaikapercent': bl});
    }
    return res ? this.success('设置成功') : this.fail('设置失败');
  }

  async getshopidAction() {
    const shopid = this.shop_userinfo.departmentid;
    return this.json({shopid: shopid});
  }

  /*
   * 获取基础设置
   */
  async getBaseConfigAction() {
    const config = await this.model('or_shop_basis').where({shopid: this.shop_userinfo.departmentid}).find();
    config.tichengarr = JSON.parse(config.tichengarr || '[]');
    return this.json(config);
  }

  /*
   * 设置基础设置
   */
  async setBaseConfigAction() {
    const data = this.post();
    data.tichengarr = JSON.stringify(data.tichengarr);
    data.shopid = this.shop_userinfo.departmentid;
    // 先查询有没有配置，有配置更新，没有配置新增
    const isexist = await this.model('or_shop_basis').where({shopid: data.shopid}).find();
    let res;
    if (!think.isEmpty(isexist)) {
      res = await this.model('or_shop_basis').where({shopid: data.shopid}).update(data);
    } else {
      res = await this.model('or_shop_basis').add(data);
    }
    return res ? this.success('更改成功') : this.fail('更改失败');
  }
}
